package common

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"

	"gopkg.in/yaml.v3"
)

type Info struct {
	UserName      string `yaml:"username" json:"username"`
	PassWord      string `yaml:"password" json:"password"`
	Server        string `yaml:"server"`
	PalPath       string `yaml:"palpath" json:"palpath"`
	CMDPath       string `yaml:"cmdpath" json:"cmdpath"`
	Duration      int    `yaml:"duration" json:"duration"`
	Mem           int    `yaml:"mem" json:"mem"`
	CloseDuration int    `yaml:"closeduration" json:"closeduration"`
	CloseMsg      string `yaml:"closemsg" json:"closemsg"`
	BakSave       int    `yaml:"baksave" json:"baksave"`
}

func getPublicIp() string {
	resp, err := http.Get("https://api.ipify.org?format=text")
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	bodyBytes, _ := io.ReadAll(resp.Body)
	publicIp := string(bodyBytes)

	return publicIp
}

func Init() {
	_, err := os.Stat("./config.yaml")
	if err != nil {
		if os.IsNotExist(err) {
			np, _ := os.Getwd()
			infs := Info{
				UserName:      "admin",
				PassWord:      "123",
				PalPath:       fmt.Sprint(np),
				Server:        getPublicIp(),
				Mem:           90,
				Duration:      5,
				CloseDuration: 10,
				BakSave:       30,
				CloseMsg:      "The server will close after 10 seconds.",
			}
			cmd := strings.Split(np, "/")
			var cmdpath string
			for k, v := range cmd[:len(cmd)-3] {
				if k == 0 {
					cmdpath += fmt.Sprint(v)
					continue
				}
				cmdpath += fmt.Sprintf("/%s", v)
			}
			infs.CMDPath = cmdpath

			out, _ := yaml.Marshal(infs)
			os.WriteFile("./config.yaml", out, 0777)
		}
	}
}
func GetInfo() *Info {
	data, err := os.ReadFile("./config.yaml")
	if err != nil {
		return &Info{}
	}
	info := &Info{}
	yaml.Unmarshal(data, info)

	return info
}

func SetInfo(info *Info) {
	out, _ := yaml.Marshal(info)
	os.WriteFile("./config.yaml", out, 0777)
}
